import axios from "axios";
import { getToken, formatToken } from "@/utils/auth";
import feedback from "@/utils/feedback";
import httpConfig from "@/utils/http/httpConfig";
//上传文件需要 token
const token = getToken();
console.log("token", token);

const uploadHeaders = {
  Authorization: formatToken(token.accessToken) || ""
};

const videoType = ["mp4", "flv", "avi"];
const imgType = ["jpg", "jpeg", "png", "gif", "bmp"];
const otherType = ["txt", "word", "excel", "pdf", "ppt", "zip", "rar", "7z"];

const checkUrlPath = (path = "", ext = ["mp4"]) => {
  const fileExtension = path.split(".").pop().toLowerCase();
  return ext.includes(fileExtension);
};

/**
 * 校验文件类型是否符合规范
 * @param type  校验类型 0:图片 1:视频 2:其他
 * @param fileName  文件名称
 */
export const checkType = (type: Number, fileName: string): Boolean => {
  if (type == 0 && checkUrlPath(fileName, imgType)) {
    return true;
  }
  if (type == 1 && checkUrlPath(fileName, videoType)) {
    return true;
  }
  if (type == 2 && checkUrlPath(fileName, otherType)) {
    return true;
  }

  return false;
};

export const uploadApi = async file => {
  const formData = new FormData();
  formData.append("file", file);
  try {
    const response = await axios.post(httpConfig.upload, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
        Authorization: uploadHeaders.Authorization
      }
    });
    console.log("File uploaded successfully:", response.data);
    let data = response.data;
    if (data.code == 200) {
      return data.data;
    }
  } catch (error) {
    console.error("Error uploading file:", error);
    feedback.msgError("上传文件失败!");
    return null;
  }
};
